<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Weibo extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        api_user_do_login();
        $access = $this->session->userdata('sina_weibo');
        // access 失效
        if (!$access || $access['expires_on'] < time()) {
            $this->session->sess_destroy();
            api_failed('access_token_expired');
        }
        try {
            $this->load->library('sina_weibo/weibo_client', 
                array($access['access_token']));
        } catch (Exception $e) {
            api_failed($e->getMessage());
        }
    }
    
    public function share_product() {
        $product_id = $this->input->post('product_id', true);
        $text = $this->input->post('text', true);
        if (empty($product_id)) {
            api_failed('empty_product_id');
        }
        $this->load->model('setting_model');
        $this->load->model('product_model');
        $pre_words = $this->setting_model->get_setting_val('pre_words_of_share');
        $picture = $this->product_model->get_product_sharing_picture($product_id);
        $share_text = $pre_words.$text;
        $img_url = FCPATH.$picture;
        $return = $this->weibo_client->share_image($share_text, $img_url);
        if (!isset($return['error'])) {
            $text = resc($text);
            $this->load->model('share_model');
            $this->load->model('vote_model');
            $create_time = date('Y-m-d H:i:s', time());
            $this->share_model->add_share($this->user->id, $product_id, $text, 
                $create_time, $return['id']);
            $this->product_model->increase_product_share_count($product_id);
            if (!$this->vote_model->has_vote($this->user->id, $product_id)) {
                $this->vote_model->add_vote($this->user->id, $product_id, 
                $create_time);
                $this->product_model->increase_product_vote_count($product_id);
            }
        }
        api_success($return);
    }

}